!function () {
    layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat','upload', 'form','status','common'], function () {
        //定义
        var $ = layui.jquery,
            table = layui.table,
            form = layui.form,
            upload = layui.upload,
            dateformat = layui.dateformat,
            laydate = layui.laydate,
            layuiSta = layui.status,//自定义状态控件
            common = layui.common;//自定义状态控件

        //定义总变量
        var Brand = {
            tableId: "brandTable",    //表格id
            menuCode :"brand",           //对应菜单授权码
            menuType:{},              //类型
            condition: {                //查询条件
                brandName: "",
                startDate: "",
                endDate: ""
            },
            editorTool :null, //富文本内容
            uploadImg : null    //上传封面base64吗
        }

        //启动富文本编辑
        var ueditor ;

        /****
         * 初始化获取类别
         */
        Brand.initType = function(){
            //初始化品牌类型
            Brand.menuType = common.getMenuWebListByCode(Brand.menuCode);
        }

        /**
         * 初始化列表列
         * **/
        Brand.initColumn = function(){
            return [[
                /*{type: 'checkbox', fixed: 'left'},*/
                {field: 'brandId', title: 'ID', width: 80, hide: true},
                {field: 'brandName', title: '品牌标题', width: 160},
                {field: 'url', title: '封面图片', width: 260, templet: '#imgRender'},
                {
                    field: 'type', title: '品牌类别', width: 120, templet: function (row) {
                        return Brand.menuType[row.type] == undefined ? "" : Brand.menuType[row.type];
                    }
                },
                {field: 'status', title: '显示', width: 120, templet: '#statusClo'},
                {
                    field: 'releaseTime', title: '发布时间', width: 165, templet: function (row) {
                        return dateformat.format(row.releaseTime, 'yyyy-MM-dd hh:mm:ss');
                    }
                },
                {field: 'createPerson', title: '创建人', width: 120},
                {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 280, align: 'center'}
            ]];
        }


        /**
         * 查询方法
         * **/
        Brand.search = function(){
            var queryData = {};
            queryData["brandName"] = $("#brandName").val();
            queryData["type"] = $("#brandType").val();
            queryData["startDate"] = $("#startDate").val();
            queryData["endDate"] = $("#endDate").val();
            table.reload(Brand.tableId, {where: queryData,page: {curr: 1}});
        }

        /**
         * 新增记录
         * **/
        Brand.addRecord =function (){

            //初始化表单

            /*laydate.render({
                elem: '#releaseTime'
            });
            //初始化表单
            $('#editForm')[0].reset();
            $('#editForm :input').val("");//重置所有的input
            //重置上传图片
            var $uploadListDiv = $('#uploadListDiv');
            var $tipUpload = $('#imgText');
            $('#uploadListDiv').empty();

            layuiSta.initSta("#statusDiv",'',true);//构建状态
            common.initMenusOptions("#type",Brand.menuCode);//构建下拉选项
            layui.form.render();
            Brand.uploadImg ='';

            //清空富文本编辑框
            ueditor = UE.getEditor('ueditorText');
            //玄学加载
            setTimeout(function(){
                ueditor.setContent("");
            },666);
            $('#ueditorText #edui1_bottombar').hide();
            //打开弹出层
            var index = layer.open({
                type: 1, maxmin: true, title: '新增品牌', shade: 0.4, shadeClose: false,
                area: ['850px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                yes: function () {
                    $('#saveRecord').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#editForm').hide();
                }
            });
            layer.full(index);*/

            window.location.href="/brand/add";
        }

        /**
         * 修改记录
         * **/
        Brand.editRecord =function (data){
            //初始化数据
            /*Brand.uploadImg ='';
            var $uploadListDiv = $('#uploadListDiv');
            var $tipUpload = $('#imgText');
            $('#uploadListDiv').empty();
            //设置富文本编辑框
            ueditor = UE.getEditor('ueditorText');
            $.ajax({
                async: false,
                url: '/brand/findBrand?brandId=' + data.brandId,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;
                        //初始化表单
                        common.initMenusOptions("#type",Brand.menuCode);//构建下拉选项
                        form.render('radio').val('editForm', data);
                        laydate.render({
                            elem: '#releaseTime'
                        });
                        //封面初始化
                        Brand.uploadImg ='';
                        //构建图片或者视频
                        var htmlDiv ='';
                        if(data.url.indexOf("image") !=-1){
                            htmlDiv +='<img id="fileDiv" src="'+data.url+'" style="height: 137px;width: 137px;"/>';
                        }
                        $uploadListDiv.empty().append(htmlDiv);

                        layuiSta.initSta("#statusDiv",data.status,true);//构建状态
                        if( data.brandText != undefined ) {
                            //玄学加载
                            setTimeout(function () {
                                ueditor.setContent(data.brandText);
                            }, 666);
                        }
                        $('#ueditorText #edui1_bottombar').hide();
                        //打开弹出层
                        var index = layer.open({
                            type: 1, maxmin: true,
                            scrollbar: false , title: '修改品牌', shade: 0.4, shadeClose: false,
                            area: ['850px', '600px'], content: $('#editForm').show(), btn: ['保存', '取消'],
                            yes: function () {
                                $('#saveRecord').click();
                            }, btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#editForm').hide();
                            }
                        });
                        layer.full(index);
                    }else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });*/
            window.location.href="/brand/update?brandId="+data.brandId;
        }

        /**
         * 删除记录
         * **/
        Brand.deleteRecord =function (data){
            $.ajax({
                async: false,
                type: 'post',
                url: '/brand/delete?brandId=' + data.brandId,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Brand.search();
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        //初始化渲染列表
        //日期
        var startDate = laydate.render({
            elem: '#startDate',
            done: function(value, date){
                endDate.config.min = date;
                endDate.config.min.month = date.month -1;
            }
        });
        var endDate =  laydate.render({
            elem: '#endDate',
            done: function(value, date){
                if($.trim(value) == ''){
                    var curDate = new Date();
                    date = {'date': curDate.getDate(), 'month': curDate.getMonth()+1, 'year': curDate.getFullYear()};
                }
                startDate.config.max = date;
                startDate.config.max.month = date.month -1;
            }
        });


        //先初始化父菜单
        Brand.initType();

        table.render({
            elem:"#brandTable"
            ,url:"/brand/listPage"
            ,cellMinWidth:80
            ,request: {pageName: 'pageNum', limitName: 'pageSize'}
            ,page: true
            ,cols:Brand.initColumn(),
            cellMinHeight:200

        });

        // 搜索按钮点击事件
        $('#btnSearch').click(function () {
            Brand.search();
        });

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');
            Brand.search();
        });

        // 添加按钮点击事件
        $('#btnAdd').click(function () {
            Brand.addRecord();
        });
        //初始化查询下拉
        common.initMenusOptions("#brandType",Brand.menuCode);//构建下拉选项

        //普通图片上传
        var uploadFileBtn = upload.render({
            elem: '#uploadBtn'
            ,url: '/upload/uploadFiles'
            ,field:"layuiFiles"
            ,accept: 'file' //普通文件
            ,auto: false    //不自动上传
            ,exts: 'jpg|png|jpeg' //只允许上传压缩文件
            ,choose: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    var $uploadListDiv = $('#uploadListDiv');
                    var $tipUpload = $('#imgText');
                    var htmlDiv ='';
                    if(file.type.indexOf("image") !=-1){
                        if( (file.size/1014).toFixed(1) > 10240 ){
                            return layer.msg("图片不能超过10M");
                            return false;
                        }
                        //限制图片尺寸
                        var img = new Image();

                        var flagUpload = true;
                        img.onload = function(){
                            if(img.width != 380 || img.height != 320){
                                layer.msg("品牌图片固定尺寸为380*320");
                                flagUpload= false;
                            }
                            uploadFileBtn.config.data ={"dir":"image"};
                            htmlDiv +='<img id="fileDiv" style="height: 137px;width: 137px;"/>';
                            if( flagUpload ){
                                $uploadListDiv.empty().append(htmlDiv);
                                //执行上传
                                obj.upload(index, file);
                            }
                        };
                        img.src = result;
                    }
                });
            }
            ,done: function(res){
                if(res.code==1){
                    layer.alert(res.message,5);
                }
                if(res.error>0){
                    return layer.msg(res.message);
                }
                if(res.error==0){
                    var $uploadListDiv = $('#uploadListDiv');
                    $("#url").val(res.url);
                    $uploadListDiv.find("#fileDiv").attr("src",res.url);
                    layer.msg("上传成功");
                }
            }
        });

        //监听工具条
        table.on('tool(' + Brand.tableId + ')',function(obj){
            var data = obj.data;
            var layEvent = obj.event;
            if( layEvent ==='detail'){
                //查看
                return false;
            } else if( layEvent ==='del'){
                layer.confirm('确定要删除该品牌内容吗？', function (index) {
                    Brand.deleteRecord(data);
                    return false;
                });
            } else if( layEvent ==='edit'){
                Brand.editRecord(data);
                return false;
            }
        });

        //监听状态操作
        form.on('switch(setStatus)', function(obj){
            $.ajax({
                async: false,
                type: 'post',
                url: '/brand/setStatus',
                data:{"id":this.value,"status":obj.elem.checked?1:0},
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.tips('修改状态成功', obj.othis);
                    }
                },
                error: function () {
                    layer.alert('修改状态失败', obj.othis);
                }
            });
        });

        //监听提交事件
        form.on('submit(editRecord)',function(data){

            //获取富文本编辑内容
            var brandText = ueditor.getContent();
            data.field['brandText']=brandText;
            var postUrl = !data.field['brandId'] ? '/brand/addBrand' : '/brand/editBrand';
            /*//获取封面图片base64
            if( Brand.uploadImg !='')
                data.field['uploadImg'] =Brand.uploadImg;*/

            if( data.field.status == "undefined" || data.field.status == null){
                layer.msg("请选择状态");
                return false;
            }
            $.ajax({
                async: false, type: 'post',
                traditional: true,
                data: JSON.stringify(data.field),
                contentType:"application/json;charset=UTF-8",
                processData:false,
                url: postUrl,
                success: function (data) {
                    if (data && data.code == 200) {
                        layer.closeAll();
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        Brand.search();
                    } else
                        layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.closeAll();
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
            return false;
        });

    });
}();